package com.michael.demos.base.java8;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;

/**
 * 类功能描述:
 * <pre>
 *   OptionalDemo
 * </pre>
 *
 * @author Michael
 * @version 1.0
 * @date 2020/8/6 16:51
 */
public class OptionalDemo {
    /**
     * 1. Optional.of() 它要求传入的 obj 不能是 null 值的, 否则还没开始进入角色就倒在了 NullPointerException 异常上了
     * 2. Optional.ofNullable() 它以一种智能的, 宽容的方式来构造一个 Optional 实例. 来者不拒, 传 null 进到就得到 Optional.empty(), 非 null 就调用
     * Optional.of(obj).
     */
    public static void main(String[] args) {
        Optional<User> user = Optional.of(new User());
        System.out.println(user.isPresent());
        user = Optional.ofNullable(null);
        //System.out.println(user.equals(Optional.empty()));
        //System.out.println(user.orElseGet(initUser()));
        //System.out.println(user.orElseGet(OptionalDemo::initUser2));
        //System.out.println(user.orElse(new User()));
        //System.out.println(user.get());
        List<String> list = user.map(User::getOrders).orElse(Arrays.asList("abc", "def"));
        System.out.println(list);
    }

    private static User initUser2() {
        return new User();
    }

    private static Supplier<User> initUser() {
        //return new Supplier<User>() {
        //    @Override
        //    public User get() {
        //        return new User();
        //    }
        //};
        //return () -> new User();
        return User::new;
    }
}

class User {
    private String name;
    private Integer age;
    private List<String> orders;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public List<String> getOrders() {
        return orders;
    }

    public void setOrders(List<String> orders) {
        this.orders = orders;
    }
}

